<template>
    <div>
        <div style="margin: 20px 20px;" class="btn_box">
            <el-button type="primary" @click="handlerAdd">新增用户</el-button>
        </div>
        <el-table :data="users" style="width: 100%;height:380px" border >
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column label="用户名" prop="username" />
            <el-table-column label="姓名" prop="name" />
            <el-table-column label="电话" prop="phone" />
            <el-table-column label="创建时间" prop="create_time" :formatter="resetDate" />
            <el-table-column label="所属角色" prop="role_id" :formatter="formatRole" />

            <el-table-column label="操作">
                <template #default="scope">
                    <el-button  @click="handleEdit(scope.row._id)">
                        编辑
                    </el-button>
                    <el-button  type="danger" @click="handleDelete(scope.row._id)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
            layout="total,sizes, prev, pager, next,jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />

        <!-- 新增或编辑用户对话框 -->
        <el-dialog v-model="addUserFormVisible" :title="title" width="500px">
            <el-form :model="user" ref="userFormRef" label-width="100px" label-position="right" style="width: 400px;"
                :rules="rules">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="user.username" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <!-- <el-input v-model="user.password" /> -->
                    <el-input v-model="user.password" type="password" show-password />
                </el-form-item>

                <el-form-item label="姓名" prop="name">
                    <el-input v-model="user.name" />
                </el-form-item>

                <el-form-item label="角色" prop="role_id">
                    <el-select v-model="user.role_id" placeholder="请点击选择">
                        <el-option v-for="role in roleOptions" :key="role._id" :label="role.name" :value="role._id" />

                    </el-select>
                </el-form-item>

                <el-form-item label="手机号码" prop="number" @keydown.enter="addData(userFormRef)">
                    <el-input v-model="user.phone" />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="addData(userFormRef)">
                        确定
                    </el-button>
                    <!-- 不用关心在关闭的时候是否清空数据，因为在打开新增用户对话框的时候已经就把数据进行了清除 -->
                    <el-button @click="addUserFormVisible = false">取消</el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>
<script setup lang="ts">
import { ElMessage, formatter, type FormInstance, type FormRules } from 'element-plus';
import { formateDate } from "@/utils/dateUtils";
//引入角色小仓库
import useRoleStore from '@/store/modules/role';
import { nextTick, onMounted, reactive, ref } from 'vue';
import type { roleInfoData } from '@/api/role/type';
const roleStore = useRoleStore();
import useUserStore from '@/store/modules/user';
import type { userInfoData } from '@/api/user/type';
const userStore = useUserStore();
//用户数据列表
const users = ref<userInfoData[] | null>()
//角色列表用户格式化角色id
let roleOptions = ref<roleInfoData[]>()



//格式化表格中的时间数据
const resetDate = (row: any, colum: any, cellValue: number, index: number) => {
    return formateDate(cellValue)
}
//格式化表格中的角色信息:角色id替换为角色名称
const formatRole = (row: any, colum: any, cellValue: string, index: number) => {
    let role = roleOptions.value?.find(item => {
        return item._id == cellValue;
    })
    return role?.name;
}
//获取角色列表
const getRoles = () => {
    roleStore.roleList().then(() => {
        roleOptions.value = roleStore.roles;
    })
}

//当前页面
const currentPage = ref(1)
//一夜显示多少条数据
const pageSize = ref(5)
//总条数
const total = ref(0)
//总条数
const totalPage = ref(1)
//显示条数大小改变的时候触发的方法
const handleSizeChange = (val: number) => {
    pageSize.value = val;
    getUserList()
    console.log(`当前一页总条数:${val}`);
}
//改变当前页面
const handleCurrentChange = (val: number) => {
    currentPage.value = val;
    getUserList()
    console.log(`当前页码:${val}`);
}

//分页获取用户列表
const getUserList = () => {
    userStore.getUserList({ page: currentPage.value, size: pageSize.value }).then((res) => {
        users.value = res?.data;
        total.value = res?.total as number;
    })
}

/* 新增用户 */
//对话框标题
const title = ref<string>()
//新增用户对话框标题
const addUserTitle = "新增用户"
//控制新增用户对话框显隐
const addUserFormVisible = ref(false)
//新增用户表单对象
const userFormRef = ref<FormInstance>()
//新增用户按钮，触发新增用户对话框
const handlerAdd = () => {
    //设置对话框标题
    title.value = addUserTitle;
    //清空user，防止from表单隐藏并未关闭数据一直存储
    user.value = {
        _id: undefined,
        username: "",
        password: "",
        name: "",
        phone: "",
        role_id: ""
    }
    addUserFormVisible.value = true;
    //清空表单数据
    nextTick(() => {
        userFormRef.value?.resetFields();
    })
}
//新增用户对象
const user = ref<userInfoData>({
    _id: "",
    username: "",
    password: "",
    name: "",
    phone: "",
    role_id: ""
})


const validateUserName = (rule: any, value: any, callback: any) => {
    value = value.trim();
    const length = value && value.length;
    const pwdReg = /^[a-zA-Z0-9_]+$/
    if (value === '') {
        callback(new Error('请输入账号'))
    } else if (length < 4 || length > 12) {
        callback(new Error("长度在4到12个字符"))
    } else if (!pwdReg.test(value)) {
        callback(new Error("账号必须是英文、数字或下划线组成"))
    } else {
        callback()
    }
}
const validatePhone = (rule: any, value: any, callback: any) => {
    value = value.trim();
    const phoneReg = /^1[3-9]\d{9}$/;
    if (value == "") {
        callback(new Error("请输入手机号码"))
    } else if (!phoneReg.test(value)) {
        callback(new Error("请输入正确的手机号码"))
    } else {
        callback();
    }
}

const rules = reactive<FormRules>({
    username: [{ validator: validateUserName, trigger: ['blur', 'change'] }],
    password: [{ required: true, message: "请输入密码", trigger: 'blur' }, { min: 3, message: "密码长度需大于4位", trigger: 'blur' }],
    name: [{ required: true, message: "请输入姓名", trigger: 'blur' }],
    rule_id: [{ required: true, message: "请输入角色", trigger: 'blur' }],
    phone: [{ required: true, validator: validatePhone, trigger: ['blur', 'change'] }],
})



const addData = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {

            if (title.value === "新增用户") {
                //发送创建用户请求
                userStore.addUser(user.value).then(() => {
                    //添加成功
                    addUserFormVisible.value = false;
                    //刷新以下用户列表
                    getUserList();
                    ElMessage({
                        type: "success",
                        message: "添加成功"
                    })
                }).catch((err) => {
                    ElMessage({
                        type: "error",
                        message: err.msg
                    })
                })

            } else if (title.value === "编辑用户") {
                //编辑用户的请求
                userStore.updateUser(user.value).then(() => {
                    //更新成功
                    addUserFormVisible.value = false;
                    //刷新以下用户列表
                    getUserList();
                    ElMessage({
                        type: "success",
                        message: "修改成功"
                    })
                }).catch((err) => {
                    ElMessage({
                        type: "error",
                        message: err.msg
                    })
                })
            }

            console.log('submit!')
        } else {
            console.log('error submit!')
        }
    })
}

/* 更新用户 */
//更新用户对话框标题
const updateUserTitle = "编辑用户"
//控制更新窗口的显隐
// const updateUser = reactive({...})
//更新方法
const handleEdit = (_id: string) => {
    title.value = updateUserTitle;
    addUserFormVisible.value = true;

    userStore.findById(_id).then((res) => {
        console.log(res);

        user.value = { ...res };
    })
}

/* 删除用户 */
const handleDelete = (_id: string) => {
    userStore.removeUser(_id).then(() => {
        //删除成功
        //刷新以下用户列表
        getUserList();
        ElMessage({
            type: "success",
            message: "删除成功"
        })
    }).catch((err)=>{
        ElMessage({
            type: "error",
            message: err.msg
        })
    })

}
onMounted(() => {
    getRoles()
    getUserList()
})

</script>

<style scoped>
.el-pagination {
    display: flex;
    justify-content: center;
}


</style>